from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class Article(db.Model):
    """文章内容表"""
    __tablename__ = 'article'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='文章ID')
    title = db.Column(db.String(100), nullable=False, comment='文章标题')
    category_id = db.Column(db.BigInteger, db.ForeignKey('article_category.id'), nullable=False, comment='分类ID')
    content = db.Column(db.Text, nullable=False, comment='文章内容')
    summary = db.Column(db.String(255), nullable=True, comment='文章摘要')
    cover_image = db.Column(db.String(255), nullable=True, comment='封面图片')
    author = db.Column(db.String(50), nullable=True, comment='作者')
    view_count = db.Column(db.Integer, nullable=False, default=0, comment='浏览次数')
    status = db.Column(db.SmallInteger, nullable=False, default=1, comment='状态：0-草稿，1-发布')
    is_top = db.Column(db.SmallInteger, nullable=False, default=0, comment='是否置顶')
    is_deleted = db.Column(db.SmallInteger, nullable=False, default=0, comment='是否删除')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    category = db.relationship('ArticleCategory', backref=db.backref('articles', lazy='dynamic'))

    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'category_id': self.category_id,
            'category_name': self.category.name if self.category else None,
            'summary': self.summary,
            'cover_image': self.cover_image,
            'author': self.author,
            'view_count': self.view_count,
            'status': self.status,
            'is_top': self.is_top,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }
    
    def to_detail_dict(self):
        result = self.to_dict()
        result['content'] = self.content
        return result


class ArticleCategory(db.Model):
    """文章分类表"""
    __tablename__ = 'article_category'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='分类ID')
    name = db.Column(db.String(50), nullable=False, comment='分类名称')
    code = db.Column(db.String(50), nullable=False, unique=True, comment='分类代码')
    parent_id = db.Column(db.BigInteger, nullable=True, comment='父分类ID')
    sort = db.Column(db.Integer, nullable=False, default=0, comment='排序')
    status = db.Column(db.SmallInteger, nullable=False, default=1, comment='状态：0-禁用，1-正常')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'code': self.code,
            'parent_id': self.parent_id,
            'sort': self.sort,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }


class Resource(db.Model):
    """资源信息表"""
    __tablename__ = 'resource'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='资源ID')
    resource_type = db.Column(db.String(20), nullable=False, comment='资源类型：image/video/ebook')
    resource_name = db.Column(db.String(100), nullable=False, comment='资源名称')
    resource_url = db.Column(db.String(255), nullable=False, comment='资源URL')
    resource_size = db.Column(db.Integer, nullable=True, comment='资源大小(KB)')
    resource_format = db.Column(db.String(20), nullable=True, comment='资源格式')
    description = db.Column(db.String(255), nullable=True, comment='资源描述')
    status = db.Column(db.SmallInteger, nullable=False, default=1, comment='状态：0-禁用，1-正常')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    def to_dict(self):
        return {
            'id': self.id,
            'resource_type': self.resource_type,
            'resource_name': self.resource_name,
            'resource_url': self.resource_url,
            'resource_size': self.resource_size,
            'resource_format': self.resource_format,
            'description': self.description,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }


class AdminUser(db.Model):
    """管理员用户表"""
    __tablename__ = 'admin_user'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='管理员ID')
    username = db.Column(db.String(50), unique=True, nullable=False, comment='用户名')
    password = db.Column(db.String(100), nullable=False, comment='密码（加密）')
    real_name = db.Column(db.String(50), nullable=True, comment='真实姓名')
    phone = db.Column(db.String(20), nullable=True, comment='手机号')
    email = db.Column(db.String(100), nullable=True, comment='邮箱')
    avatar = db.Column(db.String(255), nullable=True, comment='头像URL')
    role = db.Column(db.String(20), nullable=False, default='editor', comment='角色：admin/editor/viewer')
    status = db.Column(db.SmallInteger, nullable=False, default=1, comment='状态：0-禁用，1-正常')
    last_login_time = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
    last_login_ip = db.Column(db.String(50), nullable=True, comment='最后登录IP')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'real_name': self.real_name,
            'phone': self.phone,
            'email': self.email,
            'avatar': self.avatar,
            'role': self.role,
            'status': self.status,
            'last_login_time': self.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if self.last_login_time else None,
            'last_login_ip': self.last_login_ip,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }


class SystemConfig(db.Model):
    """系统配置表"""
    __tablename__ = 'system_config'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='配置ID')
    config_key = db.Column(db.String(50), unique=True, nullable=False, comment='配置键')
    config_value = db.Column(db.Text, nullable=False, comment='配置值')
    config_type = db.Column(db.String(20), nullable=False, comment='配置类型：system/payment/service')
    description = db.Column(db.String(255), nullable=True, comment='配置描述')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    def to_dict(self):
        return {
            'id': self.id,
            'config_key': self.config_key,
            'config_value': self.config_value,
            'config_type': self.config_type,
            'description': self.description,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }


class SystemLog(db.Model):
    """系统日志表"""
    __tablename__ = 'system_log'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='日志ID')
    user_id = db.Column(db.BigInteger, nullable=True, comment='用户ID')
    user_type = db.Column(db.String(10), nullable=False, comment='用户类型：user/admin')
    operation = db.Column(db.String(50), nullable=False, comment='操作类型')
    method = db.Column(db.String(10), nullable=False, comment='请求方法')
    url = db.Column(db.String(255), nullable=False, comment='请求URL')
    ip = db.Column(db.String(50), nullable=False, comment='IP地址')
    user_agent = db.Column(db.String(255), nullable=True, comment='用户代理')
    request_data = db.Column(db.Text, nullable=True, comment='请求数据')
    response_data = db.Column(db.Text, nullable=True, comment='响应数据')
    status = db.Column(db.SmallInteger, nullable=False, comment='状态：0-失败，1-成功')
    error_msg = db.Column(db.Text, nullable=True, comment='错误信息')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'user_type': self.user_type,
            'operation': self.operation,
            'method': self.method,
            'url': self.url,
            'ip': self.ip,
            'user_agent': self.user_agent,
            'status': self.status,
            'error_msg': self.error_msg,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }
